package com.zlsy.secondtime.threadcoreknowledge.threadobjectclasscommonmethods;

/**
 * @author zhouliang
 * @date 2020/5/16 15:23
 * <p>
 * 展示wait和notify的基本用法
 * <p>
 * 1、 研究代码的执行顺序
 * 2、证明wait是释放monitor锁的
 */
public class Wait {

    private static final Object LOCK = new Object();

    static class Thread1 extends Thread {
        @Override
        public void run() {
            synchronized (LOCK) {
                try {
                    System.out.println(Thread.currentThread().getName() + "准备释放锁");
                    LOCK.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "执行完了。");
            }
        }
    }

    static class Thread2 extends Thread {
        @Override
        public void run() {
            synchronized (LOCK) {
                LOCK.notify();
                System.out.println(Thread.currentThread().getName() + "执行完了！");
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread1 thread1 = new Thread1();
        thread1.setName("线程1");
        Thread2 thread2 = new Thread2();
        thread2.setName("线程2");

        thread1.start();
        Thread.sleep(1000);
        thread2.start();
    }
}
